package translatorplugin.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;


public class HttpRequest {

	private static final String URL_OPENTRAD = "http://www.opentrad.com:80/es/opentrad/traducir";
	
	public static String sendHttpRequest(GetData getData) throws IOException {
		final String charset = "UTF-8";
		final String contentType = "application/x-www-form-urlencoded";
		
		URLConnection conn = getUrlWithParameters(getData).openConnection();
		conn.setRequestProperty("Accept-Charset", charset);
		conn.setRequestProperty("Content-Type", contentType + ";charset=" + charset);
		conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
	    conn.setDoInput(true);
	    return readResponse(conn);
	    
		
	}
	
	private static URL getUrlWithParameters(GetData getData) throws MalformedURLException, UnsupportedEncodingException {
		return new URL(URL_OPENTRAD + "?" + getData.getDataUrlEncoded());
	}

	private static String readResponse(URLConnection conn) throws IOException {
		StringBuilder response = new StringBuilder();
		
		BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
	    String line;
	    while ((line = rd.readLine()) != null) {
	        response.append(line);	
	    }
	    rd.close();
	    
	    return URLDecoder.decode(response.toString(), "UTF-8");
	}

}
